import Vue from 'vue'
import VueRouter from 'vue-router'
// 路由懒加载
const Login = () => import('../views/login/login.vue')
const Layout = () => import('../views/layout/layout.vue')
const Images = () => import('../views/images/images.vue')
const Articles = () => import('../views/articles/articles.vue')
const Edit = () => import('../views/articles/edit.vue')
const Home = () => import('../views/home/home.vue')
const AddArticle = () => import('@/views/articles/addArticle.vue')
// const Comment = () => import('@/views/comment/comment.vue')
// const Fans = () => import('@/fans/fans.vue')
// import Settings from '@/views/settings/settings.vue'
// const Settings = () => import('@/views/settings/settings.vue')
// import Home from '@/views/home/home.vue'
// @是一个别名，表示src目录，这个功能是webpack提供的
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    // 登录页
    {
      path: '/login',
      component: Login
    },
    // 主页
    {
      path: '/',
      component: Layout,
      children: [
        { path: '', component: Home },
        { path: '/images', component: Images },
        { path: '/articles', component: Articles },
        { name: 'edit', path: '/edit/:id', component: Edit },
        { path: '/addArticle', component: AddArticle }
        // { path: '/comment', component: Comment },
        // { path: '/fans', component: Fans },
        // { path: '/settings', component: Settings }
      ]
    }
  ]
})

// 设置需要路由导航守卫的路径
const vipPages = ['/', '/articles', '/images']
// 设置路由导航守卫
// 所有路由跳转都会进入这个函数
router.beforeEach((to, from, next) => {
  // 获取本地保存的token值
  const tokenStr = localStorage.getItem('tokenStr')
  // 判断要去的页面是否需要有token值并且请求中是否有token值
  if (vipPages.includes(to.path) && !tokenStr) {
    // 不符合条件跳回登录页面
    next('/login')
  } else if (to.path === '/login' && tokenStr) {
  // 如果要去的页面是/login 并且有token
    next('/')
  } else {
    next()
  }
})

export default router

// {
//   path: '/about',
//   name: 'About',
//   // route level code-splitting
//   // this generates a separate chunk (about.[hash].js) for this route
//   // which is lazy-loaded when the route is visited.
//   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
// }
